import { defineStore } from 'pinia';
import { getUserInfo, wxappAuth } from "@/api/user";

interface AuthState {
    token?: string;
    user: Record<string, any>;
}

export const useAuthStore = defineStore({
    id: 'auth',
    state: (): AuthState => ({
        token: undefined,
        user: {},
    }),
    getters: {
        isLogin(): boolean {
            const token = this.token || uni.getStorageSync('token') ;
            return token !== undefined;
        },
    },
    actions: {
        // 登录
        login() {
            return new Promise<void>((resolve) => {
                uni.login({
                    provider: 'weixin',
                    success: function(loginRes) {
                        console.log(loginRes);
                        // 获取用户信息
                        uni.getUserInfo({
                            provider: 'weixin',
                            success: function(infoRes) {
                                console.log('用户昵称为：', infoRes);
                                wxappAuth({
                                    code: loginRes.code,
                                    encryptedData: infoRes.encryptedData,
                                    iv: infoRes.iv,
                                    spread: ''
                                }).then((res) => {
                                    const resToken = res?.data?.token;
                                    console.log('res', res, 'res.data.data.token', resToken)
                                    this.token = resToken;
                                    console.log('this.token', resToken)
                                    uni.setStorageSync('token', resToken);
                                    this.user = {
                                        name: 'info.name',
                                        passWord: 'info.passWord',
                                        phone: 17703787046,
                                        logo: 'https://img0.baidu.com/it/u=4079113664,1534334121&fm=253&fmt=auto&app=120&f=JPEG?w=400&h=400',
                                    };
                                    // getUserInfo().then(resInfo => {
                                    //     console.log('resInfo', resInfo)
                                        resolve();
                                    // })
                                })
                            }
                        });
                    }
                });
            });
        },
        layout() {
            this.token = undefined;
            this.user = {};
        },
    },
    // 本地持久化存储
    persist: {
        storage: {
            getItem: uni.getStorageSync,
            setItem: uni.setStorageSync,
        },
    },
});
